import React, { useState, useContext } from "react";
import { View, StyleSheet, Dimensions, Modal as RNModal, StatusBar, Text, Image, TouchableOpacity } from "react-native";
import { InputView, Keyboard } from 'react-native-pay-password';
import Modal from "react-native-modal";
import "@ethersproject/shims";
import { ethers } from 'ethers';
import crypto from "crypto";
import Toast from 'react-native-simple-toast'
import CommonContext from '@/utils/createContext'
import LogoImg from "@/assets/imgs/logo.png";
import { getValue, setObjectValue } from "@/utils/deviceStorage";
import api from "@/request/api";
import Loading from "@/components/LoadingModal";
import { AESdecrypt, AESencrypt } from "@/utils/util";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const LockScreenSet = () => {

    const [pwd, setPwd] = useState('')
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [oldPwd, setOldPwd] = useState('')
    const [tipInfo, setTipInfo] = useState('Please set your password')
    const [keyBoardVisible, setKeyBoardVisible] = useState(false)
    const [tipVisible, setTipVisible] = useState(false)
    const { modalVisible, setModalVisible, isReset, navigatToNext, isCreate, mnemonicStr } = useContext(CommonContext)

    const onDone = (pwd) => {
        if (pwd) {
            if (oldPwd) {
                if (oldPwd == pwd) {
                    if (isReset) {
                        hide()
                        setTipVisible(true)
                    } else {
                        hide()
                        let str = crypto.createHash('md5').update(pwd).digest('hex')
                        setObjectValue('lockPwd', str)
                        let str1 = AESencrypt(str.substring(0, 16), str.substring(16), mnemonicStr)
                        setObjectValue("mnemonicStr", str1)
                        setLoadingVisible(true)
                        setTimeout(() => {
                            checkWallet()
                        }, 1000);
                    }
                } else {
                    setTipInfo('Please set your password')
                    setOldPwd('')
                    setPwd('')
                    Toast.showWithGravity(
                        'Passwords are inconsistent',
                        Toast.SHORT,
                        Toast.CENTER)
                }
            } else {
                setTipInfo('Enter your password again')
                setOldPwd(pwd)
                setPwd('')
            }
        }
    }

    const checkWallet = () => {
        setObjectValue('coinType', 'ETH')
        if (mnemonicStr) {
            if (isCreate) {
                //新建助记词，需要先进行注册激活操作
                let wallet = ethers.Wallet.fromMnemonic(mnemonicStr);
                const publickey = wallet.publicKey
                //根据公钥生成并激活钱包接口
                let wallet_name = wallet.mnemonic.path
                api.eth_single_create(publickey, wallet_name).then(res => {
                    setLoadingVisible(false)
                    //激活钱包,获取地址接口
                    setObjectValue('selectedWallet', res)
                    setObjectValue('walletList', [{ ...res, disable: false }])
                    setModalVisible(false)
                    navigatToNext && navigatToNext()
                })
            } else {
                api.wallet_list().then(res => {
                    if (res && res.length > 0) {
                        setLoadingVisible(false)
                        setObjectValue('selectedWallet', res[0])
                        for (let i = 0; i < res.length; i++) {
                            res[i].disable = false
                        }
                        setObjectValue('walletList', res)
                        setModalVisible(false)
                        navigatToNext && navigatToNext()
                    }
                })
            }
        } else {
            setLoadingVisible(false)
        }
    }

    const onPress = (text) => {
        let nextPwd = pwd + text;
        if (nextPwd.length <= 6) {
            setPwd(nextPwd);
            if (nextPwd.length === 6) {
                onDone && onDone(nextPwd);
            }
        }
    };

    const onDelete = () => {
        setPwd(pwd.substring(0, pwd.length - 1));
    }

    const show = () => {
        setPwd('')
        setKeyBoardVisible(true)
    };

    const hide = () => {
        setKeyBoardVisible(false)
    };

    const onConfirm = () => {
        keythereum.recover()
        //取出原来的密码和助记词,更新并重新加密
        let oldPwd = getValue('lockPwd')
        let oldMnemonicStr = getValue('mnemonicStr')
        let mnemonicStr = AESdecrypt(oldPwd.substring(0, 16), oldPwd.substring(16), oldMnemonicStr)
        let str = crypto.createHash('md5').update(pwd).digest('hex')
        setObjectValue('lockPwd', str)
        let newMnemonicStr = AESencrypt(str.substring(0, 16), str.substring(16), mnemonicStr)
        setObjectValue("mnemonicStr", newMnemonicStr)
        setTipVisible(false)
        setModalVisible(false)
        navigatToNext && navigatToNext()
    }

    return (
        <RNModal
            style={{ zIndex: 99 }}
            animationType="none"
            transparent={true}
            visible={modalVisible}
            onRequestClose={() => {
                setModalVisible(!modalVisible);
            }}>
            <View style={styles.container}>
                <StatusBar backgroundColor='#FFFFFF' barStyle='dark-content' />
                <Text style={styles.title1}>{tipInfo}</Text>
                <View style={styles.pwdContent}>
                    <TouchableOpacity onPress={show} activeOpacity={0.8}>
                        <InputView
                            borderColor='#888888'
                            value={pwd}
                        />
                    </TouchableOpacity>
                </View>
                {tipInfo == 'Please set your password' && <View style={{ width: 280 * ratio }}>
                    <Text style={{ ...styles.title2, color: isReset ? '#FF6C6C' : '#646464', marginTop: 22 * ratio }}>
                        This password is used to unlock this app and transaction authorization
                    </Text>
                    <Text style={{ ...styles.title2, color: isReset ? '#FF6C6C' : '#646464', marginTop: 15 * ratio }}>
                        It is recommended that this password be set differently from the mobile phone password
                    </Text>
                    <Text style={{ ...styles.title2, color: isReset ? '#FF6C6C' : '#646464', marginTop: 15 * ratio }}>
                        Please remember your mnemonic words. You can use mnemonic words to reset your password when your password is lost
                    </Text>
                </View>}
                <View style={{ flex: 1, justifyContent: 'flex-end', marginBottom: 40 * ratio }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Image source={LogoImg} style={{ width: 20 * ratio, height: 18 * ratio }} />
                        <Text style={styles.title3}>Sectoken</Text>
                    </View>
                </View>
                {keyBoardVisible && <Keyboard onPress={onPress} onDelete={onDelete} />}
            </View >
            {loadingVisible && <Loading visible={loadingVisible} />}
            {tipVisible && <Modal
                isVisible={tipVisible}
                backdropColor='#000000'
                backdropOpacity={0.34}
                style={styles.tipContainer}
            >
                <View style={styles.tipBodyContent}>
                    <View style={{ flex: 1 }}>
                        <View style={{ marginTop: 31 * ratio, alignItems: 'center' }}>
                            <Text style={styles.title2}>
                                Password reset succeeded
                            </Text>
                        </View>
                        <View style={styles.tipDivider1}></View>
                        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                            <TouchableOpacity onPress={onConfirm}
                                style={{ width: 100 * ratio, alignItems: 'center', justifyContent: 'center' }}>
                                <Text style={{ ...styles.title2, color: '#FF6F00' }}>Confirm</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>}
        </RNModal>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF',
        alignItems: 'center'
    },
    pwdContent: {
        flexDirection: 'row',
        marginTop: 27 * ratio,
        justifyContent: 'center'
    },
    title1: {
        fontSize: 24,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#646464',
        lineHeight: 31,
        marginTop: 70 * ratio
    },
    title2: {
        fontSize: 12,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#646464',
        lineHeight: 16
    },
    title3: {
        fontSize: 14,
        fontFamily: 'Microsoft YaHei',
        fontWeight: 'bold',
        color: '#DADAE3',
        lineHeight: 19,
        marginLeft: 7 * ratio
    },
    tipContainer: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    tipBodyContent: {
        width: 240 * ratio,
        height: 108 * ratio,
        backgroundColor: '#FFFFFF'
    },
    tipDivider1: {
        width: 240 * ratio,
        height: 0,
        borderWidth: 1,
        borderColor: '#E4E4E4',
        marginTop: 24 * ratio
    }
})
export default LockScreenSet